﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;

namespace TextToSpeech.Controllers
{
    public class TextToSpeachController : ApiController
    {
        public string Get(string text)
        {
            try
            {
                if (text.Length > 65535)
                {
                    return "{\"code\":1,\"msg\":\"文字长度太长了，请将文字控制在65535个字符之内！\",\"url\":\"\"}";
                }
                string fileName = GetMD5(text);
                string filePath = System.Web.Hosting.HostingEnvironment.MapPath("/") + $"\\speech\\{fileName}.wav";
                if (System.IO.File.Exists(filePath))
                {
                    return "{\"code\":0,\"msg\":\"文件已经存在！\",\"url\":\"/speech/" + fileName + ".wav\"}";
                }
                else
                {
                    Thread thread = new Thread(() =>
                    {
                        using (SpeechSynthesizer synth = new SpeechSynthesizer())
                        {
                            synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                            PromptBuilder builder = new PromptBuilder();
                            builder.AppendText(text);
                            synth.Speak(builder);
                        }
                    });
                    thread.Start();
                    return "{\"code\":0,\"msg\":\"生成语音成功！\",\"url\":\"/speech/" + fileName + ".wav\"}";
                }
            }
            catch (Exception e)
            {
                return "{\"code\":1,\"msg\":\"生成语音异常了：" + e.Message + "！\",\"url\":\"\"}";
            }
        }

        private string GetMD5(string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;
            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }
            return byte2String;
        }
    }
}